//
//  UIImageView+kf.swift
//  Scanread
//
//  Created by Macintosh on 2023/6/21.
//

import Foundation
import UIKit
import Kingfisher
import SwifterSwift

//下次优化的，给图片加载的，添加进度条。
public extension UIImageView {
    ///数据加载有进度条的图片加载
    ///url： 图片url
    ///placeholder：图片占位图片
    ///isThumbnail：是否是缩略图，yes 是，no不是
    ///progressHandler: 进度条的回调
    ///complateHandler： 完成的回调
    func setImageUrl(_ url: String?,
                     radius: CGFloat = 0,
                     corners: RectCorner = .all,
                     placeholder: UIImage? = nil,
                     isThumbnail: Bool? = true,
                     progressHandler:((CGFloat) -> Void)? = nil,
                     transition:ImageTransition = .fade(0.25),
                     complateHandler:((UIImage?, Bool) -> Void)? = nil) {
        var source: URL?
        var updateView: UIView? = self
        while (self.width == 0 || self.height == 0) && updateView != nil {
            updateView?.layoutIfNeeded()
            updateView = updateView?.superview
        }

        guard let url = url?.trimmed.urlDecoded.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            image = placeholder;
            return
        }


//        if (isThumbnail ?? true) && !( width == 0 && height == 0) && (url.split(separator: ".").last?.lowercased() ?? "") != "gif" {
//            source = URL(string: url)?.appending("x-image-process", value: "image/resize,s_\(Int(max(width, height) * UIScreen.main.scale))")
//        }else{
            source = URL(string: url)
//        }

        guard let resultSource = source else {
            image = placeholder
            return
        }

        var op:KingfisherOptionsInfo = [KingfisherOptionsInfoItem]()
        // 设置过度动画
        op.append(.transition(transition))
        // 设置圆角
        if radius > 0 {
            let corner = RoundCornerImageProcessor(cornerRadius: radius,roundingCorners:corners)
            op.append(KingfisherOptionsInfoItem.processor(corner))
        }

        self.kf.setImage(with: resultSource, placeholder: placeholder, options: op) { receivedSize, totalSize in
            #if DEBUG
//            print("图片加载进度\(CGFloat(receivedSize)/CGFloat(totalSize))")
//            print("图片大小\(CGFloat(totalSize)/1024.0)")
            #endif
            progressHandler?(CGFloat(receivedSize)/CGFloat(totalSize))
        } completionHandler: { result in
            if case let .success(imageResult) = result {
                complateHandler?(imageResult.image, true)
            } else {
                complateHandler?(nil, false)
            }
        }

    }
    
    ///complateHandler： 完成的回调
    func setImageWith(_ url: URL?) {
        var op:KingfisherOptionsInfo = [KingfisherOptionsInfoItem]()
        // 设置过度动画
        op.append(.transition(.fade(0.25)))
        self.kf.setImage(with: url, options: op)
    }
    
    func cancelDownloadTask() {
        self.kf.cancelDownloadTask();
    }
    
    func getCacheImage(localPath: String, complete: @escaping (UIImage?)->Void) {
        KingfisherManager.shared.cache.retrieveImage(forKey: localPath, completionHandler: { result in
            if case let .success(cache) = result {
                complete(cache.image)
            }else {
                complete(nil)
            }
        })
    }
    
    func setCustomIndicator(_ customIndicator: Indicator) {
        self.kf.indicatorType = .custom(indicator: customIndicator)
    }
        
    static func retrieveImage(_ url: URL, complete: @escaping (Data?)->Void) {
        KingfisherManager.shared.retrieveImage(with: url) { result in
            if case .success(let image) = result, let imageData = image.image.jpegData(compressionQuality: 1) {
                complete(imageData)
            } else {
                complete(nil)
            }
        }
    }
    
    static func cancelAllDownloadTask() {
        KingfisherManager.shared.downloader.cancelAll()
    }

}

public extension ImageDownloader {

   static func ec_download(url: String?,complateHandler:((UIImage?, Bool) -> Void)? = nil) {
        guard let url = url,let Url = URL.init(string: url)
        else {
            complateHandler?(nil,false)
            return
        }

       self.ec_download(path: Url, complateHandler: complateHandler)
    }


    static func ec_imageCacheData(_ path: String) -> Data? {
        guard let url = URL(string: path) else { return nil }

        let pathKey = url.absoluteString.md5
        return try? ImageCache.default.diskStorage.value(forKey: pathKey)
    }


    static func ec_download(path: URL,complateHandler:((UIImage?, Bool) -> Void)? = nil) {
        let pathKey = path.absoluteString.md5
        if ImageCache.default.isCached(forKey: pathKey) {
            ImageCache.default.retrieveImageInDiskCache(forKey: pathKey) { result in
                switch result {
                case .success(let content):
                    complateHandler?(content,true)
                case .failure(_):
                    complateHandler?(nil,false)
                }
            }
            return
        }

        let options: KingfisherOptionsInfo = [
            .downloader(.default),
            .targetCache(.default),
            .preloadAllAnimationData,
            .backgroundDecode
        ]

        ImageDownloader.default.downloadImage(with: path, options: options) { result in
             switch result {
             case .success(let content):
                 ImageCache.default.storeToDisk(content.originalData, forKey: pathKey)
                 complateHandler?(content.image,true)
             case .failure(_):
                 complateHandler?(nil,false)
             }
         }
     }
}

class CustomKinfinsherCache {
    static let share:CustomKinfinsherCache = CustomKinfinsherCache()
    let cache:ImageCache = try! ImageCache.init(name: "Test", cacheDirectoryURL: CustomKinfinsherCache.getRootPath()) { (url, cache) in
        var testUrl = url
        testUrl.appendPathComponent(cache)
        return testUrl
    }


    init() {
        self.cache.diskStorage.config.expiration = .never
        print("==== \(self.cache.diskStorage.config)")
    }

   static func getRootPath() -> URL {

        let dstPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        print("dstPath === \(dstPath)")
        return URL.init(fileURLWithPath: dstPath)
    }
    
}
